﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using NPOI.XSSF.Model;
using XiAnAirport.BUS;
using XiAnAirport.Models;

namespace XiAnAirport.DAL
{
    public class NoticeDAL
    {
        public string AddNotice(NoticeInfo noticeInfo)
        {
            string strSql = string.Format("INSERT INTO notification (updateTime,content,title)VALUES({0},'{1}','{2}')", noticeInfo.updateTime, noticeInfo.content, noticeInfo.title);
            try
            {
                int count = SqlHelper<NoticeInfo>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return "fail";
            }
        }

        public string EditNotice(NoticeInfo noticeInfo)
        {
            string strSql = string.Format("UPDATE notification SET updateTime={0},content='{1}',title='{3}' WHERE id={2}", noticeInfo.updateTime, noticeInfo.content, noticeInfo.id, noticeInfo.title);
            try
            {
                if (SqlHelper<NoticeInfo>.SqlExecute(strSql))
                {
                    return "success";
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return "fail";
            }
        }

        public string DelNotice(int noticeid)
        {
            string strSql = string.Format("delete FROM notification WHERE id={0}", noticeid);
            try
            {
                int count = SqlHelper<NoticeInfo>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return "fail";
            }
        }

        public List<NoticeInfo> QueryNoticeList(NoticeInfo noticeInfo)
        {
            try
            {
                List<NoticeInfo> list = new List<NoticeInfo>();
                string strSql = "SELECT * FROM notification";
                string sqlwhere = string.Empty;
                if (!string.IsNullOrEmpty(noticeInfo.content))
                {
                    sqlwhere += " content like @content AND";
                }

                if (sqlwhere.Length > 0)
                {
                    strSql += " where" + sqlwhere.Substring(0, sqlwhere.Length - 4); ;
                }
                if (noticeInfo.Recordhead > -1 && noticeInfo.Recordtail > 0)
                {
                    strSql += " LIMIT @Recordhead,@Recordtail";
                }

                using (MySqlConnection connection = DataFactory.GetMysqlConnection())
                {
                    MySqlCommand mySqlCommand = new MySqlCommand(strSql, connection);

                    // 添加参数
                    string likename = "%" + noticeInfo.content + "%";
                    mySqlCommand.Parameters.AddWithValue("@content", $"%{likename}%");
                    mySqlCommand.Parameters.AddWithValue("@Recordhead", noticeInfo.Recordhead);
                    mySqlCommand.Parameters.AddWithValue("@Recordtail", noticeInfo.Recordtail);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCommand);
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet);
                    DataTable dataTable = dataSet.Tables[0];
                    list = ToList<NoticeInfo>(dataTable);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

        public int QueryNoticeListConut(NoticeInfo noticeInfo)
        {
            string strSql = "SELECT COUNT(1) FROM notification";
            string sqlwhere = string.Empty;
            if (!string.IsNullOrEmpty(noticeInfo.content))
            {
                sqlwhere += " content like '%" + noticeInfo.content + "%' AND";
            }
            if (sqlwhere.Length > 0)
            {
                strSql += " where" + sqlwhere.Substring(0, sqlwhere.Length - 4); ;
            }

            int count = SqlHelper<NoticeInfo>.SqlScalar(strSql);

            return count;
        }

        public string ToppingNotice(NoticeInfo noticeInfo)
        {
            string strSql = string.Format("UPDATE notification SET flag={0} WHERE id={1}", noticeInfo.flag, noticeInfo.id);
            try
            {
                if (SqlHelper<NoticeInfo>.SqlExecute(strSql))
                {
                    return "success";
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return "fail";
            }
        }

        public string BatchDelNotice(string ids)
        {
            string strSql = string.Format("delete FROM notification WHERE id in ({0})", ids);
            try
            {
                int count = SqlHelper<NoticeInfo>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public NoticeInfo LoadNotice(int noticeid)
        {
            string strSql = string.Format("SELECT * FROM notification WHERE id={0}", noticeid);
            return SqlHelper<NoticeInfo>.SqlSingleData(strSql);
        }

        public List<T> ToList<T>(DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            //确认参数有效,若无效则返回Null
            if (dt == null)
                return list;
            else if (dt.Rows.Count == 0)
                return list;
            Dictionary<string, string> dicField = new Dictionary<string, string>();
            Dictionary<string, string> dicProperty = new Dictionary<string, string>();
            Type type = typeof(T);

            //创建字段字典，方便查找字段名
            foreach (var item in type.GetFields())
            {
                dicField.Add(item.Name.ToLower(), item.Name);
            }
            //创建属性字典，方便查找属性名
            foreach (var item in type.GetProperties())
            {
                dicProperty.Add(item.Name.ToLower(), item.Name);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //字段赋值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            //dbValue = dbValue.ChangeType(memberType);
                            dbValue = Convert.ChangeType(dbValue, memberType);
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //属性赋值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        if (!theProperty.CanWrite) continue;
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theProperty.SetValue(_t, dbValue, null);
                    }
                }
                list.Add(_t);
            }
            return list;
        }
    }
}
